package com.newland.mesdk.demo.fragment;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.newland.mtype.BatteryInfoResult;
import com.newland.mtype.DeviceInfo;
import com.newland.mtype.UpdateAppListener;
import com.newland.mesdk.demo.main.R;
import com.newland.mesdk.demo.adapter.FileAdapter;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.main.MyApplication;
import com.newland.mesdk.demo.util.Const;
import com.newland.mesdk.demo.util.SharedPreferencesUtil;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF 设备终端管理模块
 */
public class TerminalManageFragment extends Fragment implements android.view.View.OnClickListener {
	private EditText edit_param_tag, edit_param_value;
	private Dialog param_dialog;
	private String SDCardPath, path;
	private String NLDPathString;
	private ListView fileListView;
	private AlertDialog showFile;
	private FileAdapter fileAdapter;
	private List<File> allFiles = new ArrayList<File>();
	private boolean isCorrect = true;
	private MainActivity mainActivity;
	private String deviceType;
	private Button btnSetTime, btnGetTime, btnSetParam, btnGetParam, btnReset, btnChoiceFire, bynGetBatary;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_ternalmanage, null);
		mainActivity = (MainActivity) getActivity();
		deviceType = SharedPreferencesUtil.getStringParam(view.getContext(), Const.DEVICETYPE);
		SDCardPath = Environment.getExternalStorageDirectory().toString();
		initTernamlMenu(view);
		return view;
	}

	public void initTernamlMenu(View view) {
		btnSetTime = (Button) view.findViewById(R.id.btn_terminal_settime);
		btnSetTime.setOnClickListener(this);

		btnGetTime = (Button) view.findViewById(R.id.btn_terminal__gettime);
		btnGetTime.setOnClickListener(this);

		btnSetParam = (Button) view.findViewById(R.id.btn_terminal_setParam);
		btnSetParam.setOnClickListener(this);

		btnGetParam = (Button) view.findViewById(R.id.btn_terminal_getparam);
		btnGetParam.setOnClickListener(this);

		btnReset = (Button) view.findViewById(R.id.btn_terminal_reset);
		btnReset.setOnClickListener(this);

		btnChoiceFire = (Button) view.findViewById(R.id.btn_terminal_choice_fire);
		btnChoiceFire.setOnClickListener(this);

		bynGetBatary = (Button) view.findViewById(R.id.btn_terminal_get_batary);
		bynGetBatary.setOnClickListener(this);

		if (deviceType.equals(Const.DeviceName.IM81)) {
			bynGetBatary.setVisibility(View.GONE);
		}else if(deviceType.equals(Const.DeviceName.N900)){
			bynGetBatary.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		if (mainActivity.isDeviceInit()) {
			if (mainActivity.processingisLocked()) {
				mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
			} else {
				mainActivity.connectDevice();
				switch (v.getId()) {
				case R.id.btn_terminal_settime:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									Date date = new Date();
									mainActivity.getController().setDeviceDate(date);
									mainActivity.showMessage("设置设备时间日期成功,设置时间日期为:" + formatDate(date), MessageTag.TIP);
									mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("设置设备时间日期异常:" + e, MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;
				case R.id.btn_terminal__gettime:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									Date getDate = mainActivity.getController().getDeviceDate();
									mainActivity.showMessage("设备时间日期为:" + formatDate(getDate), MessageTag.TIP);
									mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("获取设备时间日期异常:" + e, MessageTag.ERROR);
								mainActivity.processingUnLock();
							}


						}
					}).start();

					break;
				case R.id.btn_terminal_setParam:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.runOnUiThread(new Runnable() {
										@Override
										public void run() {
											final AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
											LayoutInflater inflater = LayoutInflater.from(mainActivity);
											final View view = inflater.inflate(R.layout.dialog_param, null);
											edit_param_tag = (EditText) view.findViewById(R.id.edit_param_tag);
											edit_param_value = (EditText) view.findViewById(R.id.edit_param_value);
											builder.setView(view);
											builder.setPositiveButton("确定", new OnClickListener() {
												@Override
												public void onClick(DialogInterface arg0, int arg1) {
													try {
														int param_tag = Integer.parseInt(edit_param_tag.getText().toString().substring(2), 16);
														byte[] param_value = edit_param_value.getText().toString().getBytes("gbk");
														mainActivity.getController().setDeviceParams(param_tag, param_value);
														mainActivity.showMessage("设置终端参数成功!", MessageTag.TIP);
														mainActivity.processingUnLock();
													} catch (Exception e) {
														mainActivity.showMessage("输入数值有误" + e.getMessage(), MessageTag.ERROR);
														mainActivity.processingUnLock();
													}
												}
											});
											builder.setNegativeButton("取消", new OnClickListener() {

												@Override
												public void onClick(DialogInterface arg0, int arg1) {
													param_dialog.dismiss();
													mainActivity.processingUnLock();
												}
											});
											param_dialog = builder.create();
											param_dialog.setTitle("参数设置");
											param_dialog.show();
											param_dialog.setCancelable(false);
											param_dialog.setCanceledOnTouchOutside(false);
										}
									});

							} catch (Exception e) {
								mainActivity.showMessage("参数设置异常:" + e, MessageTag.ERROR);
								mainActivity.processingUnLock();
							}
						}
					}).start();

					break;
				case R.id.btn_terminal_getparam:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.runOnUiThread(new Runnable() {
										@Override
										public void run() {
											final AlertDialog.Builder builder1 = new AlertDialog.Builder(mainActivity);
											LayoutInflater inflater1 = LayoutInflater.from(mainActivity);
											final View view1 = inflater1.inflate(R.layout.dialog_param, null);
											edit_param_tag = (EditText) view1.findViewById(R.id.edit_param_tag);
											LinearLayout linearlayout = (LinearLayout) view1.findViewById(R.id.linearlayout);
											linearlayout.setVisibility(View.GONE);
											builder1.setView(view1);
											builder1.setPositiveButton("确定", new OnClickListener() {
												@Override
												public void onClick(DialogInterface arg0, int arg1) {
													try {
														int param_tag = Integer.parseInt(edit_param_tag.getText().toString().substring(2), 16);
														byte[] param_value = mainActivity.getController().getDeviceParams(param_tag);
														if (param_value != null) {
															mainActivity.showMessage("参数获取成功!", MessageTag.TIP);
															mainActivity.showMessage("Tag:" + edit_param_tag.getText().toString(), MessageTag.DATA);
															mainActivity.showMessage("Value:" + new String(param_value, "gbk"), MessageTag.DATA);
															mainActivity.processingUnLock();
														} else {
															mainActivity.showMessage("参数不存在", MessageTag.TIP);
															mainActivity.processingUnLock();
														}
													} catch (Exception e) {
														mainActivity.showMessage("获取参数异常" + e.getMessage(), MessageTag.ERROR);
														mainActivity.processingUnLock();
													}
												}
											});
											builder1.setNegativeButton("取消", new OnClickListener() {

												@Override
												public void onClick(DialogInterface arg0, int arg1) {
													param_dialog.dismiss();
													mainActivity.processingUnLock();
												}
											});

											param_dialog = builder1.create();
											param_dialog.setTitle("获取参数");
											param_dialog.show();
											param_dialog.setCancelable(false);
											param_dialog.setCanceledOnTouchOutside(false);
										}
									});

							} catch (Exception e) {
								mainActivity.showMessage("参数获取异常:" + e, MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;

				case R.id.btn_terminal_choice_fire:
					try {
						mainActivity.processingLock();
						selectFirmware();
					} catch (Exception e) {
						mainActivity.showMessage("选择固件异常：" + e, MessageTag.ERROR);
						mainActivity.processingUnLock();
					}

					break;
				case R.id.btn_terminal_reset:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
									mainActivity.processingLock();
									mainActivity.getController().reset();
									mainActivity.showMessage("撤销当前指令成功", MessageTag.TIP);
									mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("撤销当前指令失败", MessageTag.TIP);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;
				case R.id.btn_terminal_get_batary:
					new Thread(new Runnable() {

						@Override
						public void run() {
								mainActivity.processingLock();
								BatteryInfoResult bir = mainActivity.getController().getBatteryInfo();
								mainActivity.showMessage("电池电量信息为:" + bir.getElectricBattery() + "\r\n", MessageTag.DATA);
								mainActivity.showMessage("电源充电状态:" + bir.getChargeStatus() + "\r\n", MessageTag.DATA);
								mainActivity.showMessage("非接key模式:" + bir.getUsbStatus(), MessageTag.DATA);
								mainActivity.processingUnLock();


						}
					}).start();

					break;

				default:
					break;
				}
			}
		} else {
			mainActivity.showMessage("设备未初始化，请先初始化！", MessageTag.TIP);
		}

	}


	private String formatDate(Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(date);
		return dateString;
	}

	/**
	 * 选择固件
	 */
	public void selectFirmware() {
		fileListView = new ListView(mainActivity);
		allFiles = updatePath(((MyApplication) mainActivity.getApplication()).getNLDPath());
		if (allFiles.size() == 0) {
			mainActivity.showMessage("指定目录下无更新文件，请手动选择", MessageTag.TIP);
			allFiles = updatePath(SDCardPath);
			mainActivity.processingUnLock();
		}
		fileAdapter = new FileAdapter(allFiles, mainActivity);
		fileListView.setAdapter(fileAdapter);
		fileListView.setPadding(5, 10, 0, 10);
		fileListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
				File file = (File) fileAdapter.getItem(position);
				if (file.isFile()) {
					if (!file.getName().endsWith(".NLP") && !file.getName().endsWith(".NLD")) {
						mainActivity.showMessage("请选择正确的固件进行更新", MessageTag.TIP);
						isCorrect = false;
						mainActivity.processingUnLock();
					} else {
						String file_name = file.getName().substring(0, file.getName().lastIndexOf("."));
						String temp[] = file_name.split("_");
						String newAppVer = temp[3];
						DeviceInfo deviceInfo = mainActivity.getController().getDeviceInfo();
						String oldAppVer = deviceInfo.getAppVer();
						NLDPathString = file.getPath();
						mainActivity.showMessage("文件路径:" + NLDPathString, MessageTag.DATA);
						mainActivity.showMessage("文件大小:" + file.length(), MessageTag.DATA);
						((MyApplication) mainActivity.getApplication()).setNLDPathString(NLDPathString);
					}
					showFile.dismiss();
					updataFaire();
				} else if (file.isDirectory()) {
					allFiles.clear();
					allFiles.addAll(updatePath(file.getPath()));
					fileAdapter.notifyDataSetChanged();
				}
				mainActivity.processingUnLock();

			}
		});
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				showFile = new AlertDialog.Builder(mainActivity).setTitle("请选择固件：").setView(fileListView).setNegativeButton("取消", null).create();
				showFile.show();
			}
		});
		((MyApplication) mainActivity.getApplication()).setNLDPathString(NLDPathString);

	}

	/**
	 * 固件更新路径
	 * 
	 * @param path
	 * @return
	 */
	private List<File> updatePath(String path) {
		File[] files = new File(path).listFiles();
		ArrayList<File> allFiles = new ArrayList<File>();
		if (files.length > 0) {
			ArrayList<File> isFiles = new ArrayList<File>();
			ArrayList<File> isFolder = new ArrayList<File>();
			for (File file : files) {
				if (file.isFile() && (file.getName().endsWith(".NLD") || file.getName().endsWith(".NLP"))) {
					isFiles.add(file);
				} else if (file.isDirectory()) {
					isFolder.add(file);
				}
			}
			allFiles.addAll(isFiles);
			allFiles.addAll(isFolder);
		}
		return allFiles;
	}
	
	/**
	 * 固件更新
	 * 
	 */
	public void updataFaire() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					mainActivity.processingLock();
					if (isCorrect) {
						mainActivity.getController().updateApp(((MyApplication) mainActivity.getApplication()).getNLDPathString(),
								new UpdateAppListener() {

									@Override
									public void onUpdateProgress(long percent, long currentSize) {
										mainActivity.showMessage("固件更新进度:" + percent + "%" + " 当前完成文件大小:" + currentSize, MessageTag.DATA);
										Editor editor = mainActivity.getSharedPreferences("offset", Context.MODE_WORLD_READABLE).edit();
										editor.putInt("offset", (int) currentSize);
										editor.commit();

									}

									@Override
									public void onDownloadStart(long fileSize) {
										mainActivity.showMessage("开始更新固件,文件总大小:" + fileSize + " 字节", MessageTag.DATA);
									}

									@Override
									public void onDownloadError(String msg, Throwable e) {
										e.printStackTrace();
										mainActivity.showMessage("更新固件失败!" + e.getMessage(), MessageTag.ERROR);
										mainActivity.processingUnLock();
									}

									@Override
									public void onDownloadComplete() {
										Editor editor = mainActivity.getSharedPreferences("offset", Context.MODE_WORLD_READABLE).edit();
										editor.putInt("offset", 0);
										editor.commit();
										mainActivity.showMessage("更新固件成功!", MessageTag.TIP);
									}
								}, mainActivity.getSharedPreferences("offset", Context.MODE_WORLD_READABLE).getInt("offset", 0));
						mainActivity.processingUnLock();
					} else {
						mainActivity.showMessage("请先选择固件", MessageTag.TIP);
						mainActivity.processingUnLock();
					}

				} catch (Exception e) {
					mainActivity.showMessage("更新固件异常：" + e, MessageTag.ERROR);
					mainActivity.showMessage("请重新先选择固件", MessageTag.TIP);
					mainActivity.processingUnLock();
				}
			}
		}).start();

	}

}
